const express = require('express')
const app = express()
const port = 3000

// 使用 JSON 中间件解析请求体
app.use(express.json())

// 模拟全局变量
let flag = 1

/**
 * GET 请求：获取单个待办事项
 */
app.get('/todos/:id', (req, res) => {
  const id = req.params.id
  console.log(`Received request for /todos/${id}`)

  let timeOut = 200 // 默认延迟 200ms
  if (flag++ === 1) {
    timeOut = 3000 // 模拟第一次请求的延迟为 3s
  } else {
    flag = 1
  }

  setTimeout(() => {
    res.json({
      userId: 1,
      id: parseInt(id),
      title: `Item ${id}`,
      completed: false
    })
  }, timeOut)
})

/**
 * POST 请求：创建一个新的待办事项
 */
app.post('/todos', (req, res) => {
  const { name } = req.body
  console.log(`Received POST request to create todo: ${name}`)

  setTimeout(() => {
    res.status(200).json({
      id: Math.floor(Math.random() * 1000), // 随机生成 ID
      name,
      completed: false
    })
  }, 200) // 延迟 200ms 模拟网络延迟
})

/**
 * PUT 请求：更新一个待办事项
 */
app.put('/todos/:id', (req, res) => {
  const id = req.params.id
  const { name, completed } = req.body
  console.log(`Received PUT request to update todo with ID: ${id}`)

  setTimeout(() => {
    res.json({
      id: parseInt(id),
      name,
      completed
    })
  }, 200) // 延迟 200ms 模拟网络延迟
})

/**
 * DELETE 请求：删除一个待办事项
 */
app.delete('/todos/:id', (req, res) => {
  const id = req.params.id
  console.log(`Received DELETE request for todo with ID: ${id}`)

  setTimeout(() => {
    res.json({
      message: `Todo with ID ${id} deleted successfully`
    })
  }, 200) // 延迟 200ms 模拟网络延迟
})

/**
 * 模拟长时间运行的请求（用于测试取消请求）
 */
app.post('/long-running', (req, res) => {
  const { id } = req.body
  console.log('Received request for /long-running,id:', id)
  if (id === 1) {
    const timeout = setTimeout(() => {
      res.json({
        message: 'Long running request completed'
      })
    }, 5000) // 延迟 5s 模拟长时间运行
    // 监听客户端断开连接
    req.on('close', () => {
      console.log('Client aborted the request')
      clearTimeout(timeout)
      res.status(499).end() // 自定义状态码 499 表示客户端关闭连接
    })
  } else {
    res.json({
      message: 'Long running request completed'
    })
  }
})

/**
 * 模拟错误响应
 */
app.get('/error', (req, res) => {
  console.log('Received request for /error')

  setTimeout(() => {
    res.status(500).json({
      error: 'Internal Server Error',
      message: 'Something went wrong on the server'
    })
  }, 200) // 延迟 200ms 模拟网络延迟
})

/**
 * 模拟超时响应
 */
app.get('/timeout', (req, res) => {
  console.log('Received request for /timeout')

  setTimeout(() => {
    res.status(408).json({
      error: 'Request Timeout',
      message: 'The request took too long to process'
    })
  }, 6000) // 延迟 6s 模拟超时
})

// 启动服务器
app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`)
})
